<template>
  <div>
    <ul class="todo-main">
      <Item v-for="item in todoList" :key="item.id" v-bind="item" />
    </ul>
  </div>
</template>

<script>
import Item from "@/components/Item.vue";
export default {
  name: "List",
  components: { Item },
  data() {
    return {
      todoList: [],
    };
  },

  mounted() {
    //绑定addTodoList的自定义事件  //添加
    this.$bus.$on("addTodoList", this.addTodoList);
    // 单个删除
    this.$bus.$on("deleteSingleById", this.deleteSingleById);
    // 单个修改
    this.$bus.$on("updateSingleDoneById", this.updateSingleDoneById);
    // console.log(this.$bus.$on);
    // 全部修改
    this.$bus.$on("updateAllChecked", this.updateAllChecked);

    //删除全部选中
    this.$bus.$on("deleteAllChecked", this.deleteAllChecked);
  },
  methods: {
    // 添加
    addTodoList(newTodo) {
      if (!newTodo.todo.trim()) {
        alert("输入不能为空");
        return;
      }
      const result = this.todoList.find(
        (item) => item.todo === newTodo.todo.trim()
      );
      if (result) {
        alert("输入的内容不能重复");
        return;
      }
      this.todoList.unshift(newTodo);
    },
    //根据id单个删除
    deleteSingleById(id) {
      this.todoList = this.todoList.filter((item) => item.id !== id);
    },
    //根据id修改单个done
    updateSingleDoneById(id) {
      this.todoList.forEach((item) => {
        if (item.id === id) {
          item.done = !item.done;
        }
      });
    },

    //全部修改
    updateAllChecked(isChecked) {
      this.todoList.forEach((item) => {
        item.done = isChecked;
      });
    },

    //删除全部选中
    deleteAllChecked() {
      this.todoList = this.todoList.filter((item) => !item.done);
    },
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>